package com.kingtone.rongji.network;

import org.apache.http.Header;
import org.apache.http.HttpStatus;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.kingtone.rongji.biz.CommonMessage;
import com.kingtone.rongji.tool.RongJiUtils;
import com.loopj.android.http.BaseJsonHttpResponseHandler;

public class CommonRequest {

	public BaseJsonHttpResponseHandler createCommonHandler(
			final IRequestHandler restClient, final boolean showProgress) {
		BaseJsonHttpResponseHandler handler = new BaseJsonHttpResponseHandler() {
			
			@Override
			public void onStart() {
				if(showProgress)
				{
					RongJiUtils.showEmptyProgress(restClient.getContext());
				}
			}
			
			@Override
			public void onFailure(int statusCode, Header[] header, Throwable throwable,
					String arg3, Object arg4) {
				// TODO Auto-generated method stub
				if(showProgress)
				{
					RongJiUtils.dismissProgress();
				}
				if (null != throwable) {
					throwable.printStackTrace();
				}
				restClient.onNetworkFailure();
			}

			@Override
			public void onSuccess(int statusCode, Header[] header, String responseString,
					Object arg3) {
				// TODO Auto-generated method stub
				if(showProgress)
				{
					RongJiUtils.dismissProgress();
				}
				if (statusCode == HttpStatus.SC_OK) 
				{
					try {
						CommonMessage common = (CommonMessage) parseResponse(responseString, false);
						if (common != null) {
							if (common.getStatus()) {
								restClient.onBussinessSuccess(common);
								return;
							} else{
								restClient.onBussinessError(common
										.getErrorMessage());
								return;
							}
						}
					} catch (Throwable e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				restClient.onNetworkFailure();
			}

			@Override
			protected Object parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				// TODO Auto-generated method stub
				Gson gson = new Gson();
				JsonParser parser = new JsonParser();
				JsonElement elment = parser.parse(rawJsonData);
				CommonMessage common = gson.fromJson(elment, CommonMessage.class);
				return common;
			}
		};

		return handler;
	}
}
